package com.kuang.test1;


import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxy implements MethodInterceptor {

    private Object proxy;

    private Runnable before;

    private Runnable after;

    public CglibProxy(Class clazz, Runnable before, Runnable after) {
        Enhancer enhancer = new Enhancer();
        //设置需要创建的子类
        enhancer.setSuperclass(clazz);
        //通过字节码技术动态创建子类实例
        enhancer.setCallback(this);
        this.proxy = enhancer.create();
        this.before = before;
        this.after = after;
    }

    public CglibProxy(Class clazz) {
        Enhancer enhancer = new Enhancer();
        //设置需要创建的子类
        enhancer.setSuperclass(clazz);
        //通过字节码技术动态创建子类实例
        enhancer.setCallback(this);
        this.proxy = enhancer.create();
    }

    public Object getProxy() {
        return proxy;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        if(before != null){
            before.run();
        }
        Object result = methodProxy.invokeSuper(o, objects);
        if(after != null){
            after.run();
        }
        return result;
    }
}
